package com.huluobo.a2201mvvm_imdemo.conversation;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.huluobo.a2201mvvm_imdemo.R;
import com.huluobo.a2201mvvm_imdemo.adapter.ConversationAdapter;
import com.huluobo.a2201mvvm_imdemo.databinding.FragmentMyConversationBinding;
import com.huluobo.a2201mvvm_imdemo.mvvm.BaseMVVMFragment;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MyConversationFragment extends BaseMVVMFragment<FragmentMyConversationBinding, ConversationViewModel> {

    //列表形式还是需要一个数据源
    private List<EMConversation> emConversationList = new ArrayList<>();

    private ConversationAdapter conversationAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my_conversation;
    }

    @Override
    protected void initData() {
        viewModel.loadConversations();

        viewModel.loadConversationsSuccess.observe(this, stringEMConversationMap -> {
            dataBinding.conversationSrl.setRefreshing(false);
            emConversationList.clear();
            //一个map他所有的值(value) 是可以直接赋值给一个list的,map中是KV,values就是一个map中所有的值
            emConversationList.addAll(stringEMConversationMap.values());
            conversationAdapter.notifyDataSetChanged();
        });

        viewModel.loadConversationsFailed.observe(this, s -> {
            dataBinding.conversationSrl.setRefreshing(false);
            Log.i("TagA", "读取会话列表失败:" + s);
        });
    }

    //当Fragment恢复显示的时候,重新获取会话列表数据
    @Override
    public void onResume() {
        super.onResume();
        viewModel.loadConversations();
    }

    @Override
    protected void initView() {
        dataBinding.conversationRv.setLayoutManager(new LinearLayoutManager(requireContext()));
        conversationAdapter = new ConversationAdapter(emConversationList);
        dataBinding.conversationRv.setAdapter(conversationAdapter);

        dataBinding.conversationSrl.setOnRefreshListener(() -> {
            viewModel.loadConversations();
        });

        //添加消息监听器,用于接收到消息时,刷新适配器重新读取消息列表
        EMClient.getInstance().chatManager().addMessageListener(messages -> {
            viewModel.loadConversations();
        });
    }

    @Override
    protected Class<ConversationViewModel> getViewModel() {
        return ConversationViewModel.class;
    }
}